package com.ant.cn.duomen01;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.dow.android.DOW;
import cn.dow.android.listener.DataListener;



/**
 * 数据模式Demo:示范普通、深度任务列表数据请求
 * 
 * @author liaonaibo@domob.cn
 * @Date 2015年4月13日 上午11:32:40
 */
@SuppressLint("HandlerLeak")
@SuppressWarnings("unchecked")
public class ShowOfferListActivity extends Activity implements OnScrollListener {

	private final static int LISTVIEWLOADINGDATA = 1;
	private final static int LISTVIEWCHANGEDATA = 2;

	private LinearLayout ll_back;
	private TextView tv_title;
	private TextView tv_point;
	private ListView mListView;
	/** 数据集合 */
	private List<Map<String, Object>> mData;
	/** 数据适配器 */
	private OfferListAdapter mAdapter;
	/** 加载更多页面 */
	private View mMoreView;
	/** 是否最后一页 */
	private boolean mIsLastPage = false;
	/** 数据加载类型 0 == 普通任务列表 || 1 == 深度任务列表 */
	private int loadType = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_layout_offer_list);
		initVariable();
		initLayout();
		
		/**
		 * 在积分墙列表打开时，并且在数据加载前调用(重要，调用一次即可，刷新数据时不用再次调用)，标识打开一次积分墙，否则报错。
		 */
		DOW.getInstance(this).onAOWLaunch();
		
		loadData();
	}

	/**
	 * 初始化成员变量
	 */
	private void initVariable() {
		mData = new ArrayList<Map<String, Object>>();
		// 获取加载类型
		loadType = this.getIntent().getIntExtra("LOADINGFLAG", 0);

		DOW.getInstance(this).addMissionListener(this, mListener);
	}

	/**
	 * 监听是否有任务完成。通过包名回调通知开发者
	 */
	private DataListener mListener = new DataListener() {

		@Override
		public void onResponse(Object... arg0) {
			if (null != arg0) {
				// 获取已完成任务的包名
				String packetName = (String) arg0[0];
				Toast.makeText(getBaseContext(),
						"包名:" + packetName + " 的任务已完成,请刷新列表",
						Toast.LENGTH_SHORT).show();

				refreshData();
			}
		}

		@Override
		public void onError(String arg0) {
		}
	};

	/**
	 * 刷新数据
	 */
	private void refreshData() {
		mData.clear();
		mAdapter.notifyDataSetChanged();
		loadData();
	}

	/**
	 * 初始化布局
	 */
	private void initLayout() {
		ll_back = (LinearLayout) findViewById(R.id.more_activity_title_ll_back);
		ll_back.setOnClickListener(backClcik);
		tv_title = (TextView) findViewById(R.id.more_activity_title_tv_content);
		tv_point = (TextView) findViewById(R.id.dm_layout_offer_list_tv_point);
		tv_point.setVisibility(View.VISIBLE);
		tv_point.setText("加载中...");
		mListView = (ListView) findViewById(R.id.dm_layout_offer_list_lv);
		mMoreView = getLayoutInflater().inflate(R.layout.dm_layout_loading, null);
		mMoreView.setClickable(false);
		mListView.addFooterView(mMoreView);
		mListView.setOnScrollListener(this);
		mListView.setOnItemClickListener(adListItemClick);
		mAdapter = new OfferListAdapter(ShowOfferListActivity.this, mData);
		mListView.setAdapter(mAdapter);

		if (loadType == 0) {
			tv_title.setText("广告任务列表");
		} else if (loadType == 1) {
			tv_title.setText("签到任务列表");
		}
	}

	/**
	 * 加载数据
	 */
	private void loadData() {
		if (loadType == 0) {
			loadingAdListData(0);
		} else if (loadType == 1) {
			loadingReopenListData(0);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		/**
		 * 在积分墙列表打开时调用(重要)
		 */
		DOW.getInstance(this).onAOWLaunch();
	}

	/**
	 * 请求任务列表
	 * 
	 * @param adSize
	 *            adSize 为请求广告的总数 即：现在已展现的所有广告数量
	 */
	private void loadingAdListData(int adSize) {
		DOW.getInstance(this).getNormalAdList(this, adSize, new DataListener() {

			@Override
			public void onResponse(Object... arg0) {
				if (null != arg0) {
					List<Map<String, Object>> list = (List<Map<String, Object>>) arg0[0];
					// 是否最后一页数据
					mIsLastPage = (Boolean) arg0[1];
					if (null != list) {
						mData.addAll(list);
						mAdapter.notifyDataSetChanged();
					}
				}
			}

			@Override
			public void onError(String arg0) {
				Toast.makeText(ShowOfferListActivity.this, arg0, Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 请求签到任务列表
	 * 
	 * @param adSize
	 *            adSize 为请求广告的总数 即：现在已展现的所有广告数量
	 */
	private void loadingReopenListData(int adSize) {
		DOW.getInstance(this).getReopenAdList(this, adSize, new DataListener() {

			@Override
			public void onResponse(Object... arg0) {
				if (null != arg0) {
					List<Map<String, Object>> list = (List<Map<String, Object>>) arg0[0];
					// 是否最后一页数据
					mIsLastPage = (Boolean) arg0[1];
					if (null != list) {
						mData.addAll(list);
						mAdapter.notifyDataSetChanged();
					}
					if (mIsLastPage) {
						Toast.makeText(getBaseContext(), "最后一页了!!!",
								Toast.LENGTH_SHORT).show();
					}
				}
			}

			@Override
			public void onError(String arg0) {
				Toast.makeText(getParent(), arg0, Toast.LENGTH_SHORT).show();
			}
		});
	}

	OnItemClickListener adListItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			itemClick(position);
		}
	};

	/**
	 * 列表点击的处理，列表点击后请先调用 mDInterface.adListItemClick() 如果有广告返回才跳转详情页
	 * 
	 * @param position
	 */
	private void itemClick(int position) {
		// 启动详情界面
		Map<String, Object> obj = mData.get(position);
		int id = (Integer) obj.get("id");
		String packetName = (String) obj.get("pack_name");
		if (loadType == 1) {
			// 如果加载的是深度任务列表
			DOW.getInstance(this).download(this, id, packetName);
		} else {
			Intent intent = new Intent(ShowOfferListActivity.this,
					AppDetailActivity.class);
			intent.putExtra("id", id);
			startActivity(intent);
		}
	}

	/**
	 * 列表滑动的监听
	 */
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (mListView.getLastVisiblePosition() == (mListView.getCount() - 1)
				&& scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& !mIsLastPage) {
			if (mMoreView.getVisibility() != View.VISIBLE) {
				mMoreView.setVisibility(View.VISIBLE);
				mHandler.sendEmptyMessage(LISTVIEWLOADINGDATA);
			}
		}
	}

	/**
	 * 列表滑动的监听
	 */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	OnClickListener backClcik = new OnClickListener() {
		@Override
		public void onClick(View v) {
			ShowOfferListActivity.this.finish();
		}
	};

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case LISTVIEWLOADINGDATA: // 加载数据
				if (loadType == 0) {
					loadingAdListData((mData.size()));
				} else if (loadType == 1) {
					loadingReopenListData((mData.size()));
				}

				break;
			case LISTVIEWCHANGEDATA: // 刷新列表
				if (mAdapter != null)
					mAdapter.notifyDataSetChanged();
				break;
			}
		}
	};

	@Override
	protected void onDestroy() {
		/**
		 * 积分墙界面销毁时调用(重要)
		 */
		DOW.getInstance(this).onAOWExit();
		super.onDestroy();
	}
}
